package com.tanhua.service;


import com.tanhua.config.template.FaceTemeplate;
import com.tanhua.config.template.OssTemeplate;
import com.tanhua.config.template.SendMessageTemeplate;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.exception.BusinessExecption;
import com.tanhua.model.domain.ErrorResult;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.utils.JwtUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {
    @Autowired
    private SendMessageTemeplate sendMessageTemeplate;//发送短信
    @Autowired
    private RedisTemplate<String,String> redisTemplate;//redis




    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private UserApi userApi;


    public void sendMs(String phone) {
//        1.生成6位随机数字
        String code = RandomStringUtils.randomNumeric(6);
//        2.发送验证码到指定手机号

     //   sendMessageTemeplate.sms(code,phone);

        code="123456";
//        3.将验证码存入redis
       redisTemplate.opsForValue().set("CHECK_CODE_"+phone,code, Duration.ofMinutes(5));
    }

    /**
     * 登录验证
     * @param phone
     * @param code
     * @return
     */
    public Map loginVerification(String phone, String code) {
        //1.查找redis数据库，
        String rediscode = redisTemplate.opsForValue().get("CHECK_CODE_" + phone);
        //2.判断验证码是否存在或失效
        if (rediscode.isEmpty() || !rediscode.equals(code)){
            System.out.println("验证失败");
            //验证码失效
            throw new BusinessExecption(ErrorResult.loginError());
        }
        //3.删除redis数据
        redisTemplate.delete("CHECK_CODE_"+phone);

        //4.查询是否是新用户
        User user = userApi.findByMobile(phone);

        boolean isNew = false;
       if (user==null){
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew=true;//新用户
       }

       Map tokenMap = new HashMap();
       tokenMap.put("id",user.getId());
       tokenMap.put("mobile",phone);

        String token = JwtUtils.getToken(tokenMap);

        Map retMap = new HashMap();
        retMap.put("token",token);
        retMap.put("isNew",isNew);

        return retMap;
    }

}
